package cn.chint.controller;

import cn.chint.model.User;
import cn.chint.service.UserService;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//import org.apache.log4j.Logger;

@RestController
@RequestMapping("/db")
public class TestDBController {

	@Autowired
	UserService userService;
	//public Logger log = Logger.getLogger(getClass());
	private static final Logger logger = LogManager.getLogger(TestDBController.class);

	@GetMapping("addUser")
	public String addUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		User  u = new User();
		u.setName("测试111");
		u.setAge(22);
		try {
			userService.addUser(u);
			logger.info("添加成功");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "添加成功";
	}
	@GetMapping("selectUser")
	public String selectUser(@RequestParam(value="name",required = true) String name) throws IOException {

		    logger.info("name="+name);
		    List<User>  list  = userService.selectUser(name);
		    for(User u:list){
				logger.info(u.getId());
				logger.info(u.getAge());
				logger.info(u.getName());
				logger.info("--------------------------------");
			}
			logger.info("查询成功");

		return "查询成功";
	}
	@GetMapping("selectUser_by_id")
	public Map selectUser_by_id(@RequestParam(value="id",required = true) Long id) throws IOException {

		logger.info("id="+id);
		logger.info("--------------------------------");

		User  u  = userService.selectUser_by_id(id);
		logger.info(u.getId());
		logger.info(u.getAge());
		logger.info(u.getName());

		logger.info("查询成功");

		//ResultUtil.error(1, "账号名字已存在");
		Map<String,Object> map = new HashMap<>();
		map.put("code",0);
		map.put("status",true);
		map.put("user",u);

		return map;
	}

	@GetMapping("updateUser_by_id")
	public Map updateUser_by_id(@RequestParam(value="id",required = true) Long id,@RequestParam(value="age",required = true) int age) {
		Map<String,Object> map = new HashMap<>();
		try {
			int n  = userService.updateUser_by_id(id,age);
			map.put("更新行数",n);
			map.put("msg","更新成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	@GetMapping("deleteUser_by_id")
	public Map deleteUser_by_id(@RequestParam(value="id",required = true) Long id) {
		Map<String,Object> map = new HashMap<>();
		try {
			int n  = userService.deleteUser_by_id(id);
			map.put("删除记录数",n);
			map.put("msg","删除成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

}





